package com.dapeis.web.wx.utils.threadloca;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ag.utils.NumberUtils;
import com.ag.utils.SpringUtils;
import com.dapeis.domain.User;
import com.dapeis.service.UserService;

/**
 * 
 * Title:UserThreadLocal.java UserThreadLocal Description:
 * 
 * @author yuanyong
 * @date 2017年5月3日 上午9:27:34 Email: hzyuanyong@126.com
 *
 */

public class WxUserThreadLocal extends ThreadLocal<User> {
    public final Logger logger = LoggerFactory.getLogger(getClass());
    ThreadLocal<String> userIdThreadLocal = new ThreadLocal<String>();

    public WxUserThreadLocal() {
    }

    public WxUserThreadLocal(String openId) {
    }

    @Override
    public User get() {
	User user = super.get();
	if (user == null) {
	    logger.warn("user is null.");
	}
	return user;
    }

    @Override
	protected User initialValue() {
		String openId = userIdThreadLocal.get();
		if(StringUtils.isBlank(openId)) {
			return null;
		}
		
		UserService userService = SpringUtils.getBean(UserService.class);
		User user = userService.getUserByWeixinOpenId(openId);
		
		if(user == null) {
			logger.warn("不存在的用户:" + openId);
		}
		
		return user;
	}

    @Override
    public void remove() {
	super.remove();
	this.userIdThreadLocal.remove();
    }

    public void resetUserId(String openId) {
	this.remove();
	this.userIdThreadLocal.set(openId);
    }
}